package com.zzzs.threaddemo;

import lombok.SneakyThrows;

import java.util.concurrent.Semaphore;

/**
 * @author zhu_shuai
 * @since 9/2
 */
public class Demo02_Semaphore {
    private static Semaphore semaphore1 = new Semaphore(1);
    private static Semaphore semaphore2 = new Semaphore(0);
    private static Semaphore semaphore3 = new Semaphore(0);

    public static void main(String[] args) {
        MyRunableA a = new MyRunableA("A");
        MyRunableB b = new MyRunableB("B");
        MyRunableC c = new MyRunableC("C");

        Thread thread = new Thread(a);
        thread.start();
        Thread thread1 = new Thread(b);
        thread1.start();
        Thread thread2 = new Thread(c);
        thread2.start();

    }

    static class MyRunableA implements Runnable{

        private String name;
        public MyRunableA(String name) {
            this.name = name;
        }

        @SneakyThrows
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                semaphore1.acquire();
                System.out.print("A");
                semaphore2.release();
            }
            // System.out.printf("thread - %s %n", this.name);
        }
    }

    static class MyRunableB implements Runnable{

        private String name;
        public MyRunableB(String name) {
            this.name = name;
        }

        @SneakyThrows
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                semaphore2.acquire();
                System.out.print("B");
                semaphore3.release();
            }
            // System.out.printf("thread - %s %n", this.name);
        }
    }

    static class MyRunableC implements Runnable{

        private String name;
        public MyRunableC(String name) {
            this.name = name;
        }

        @SneakyThrows
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                semaphore3.acquire();
                System.out.print("C");
                semaphore1.release();
            }
            // System.out.printf("thread - %s %n", this.name);
        }
    }
}
